from flask import Blueprint, request, render_template, jsonify
from sqlalchemy import desc
from applications.common.utils.http import table_api
from applications.common.utils.rights import authorize
from applications.extensions import db
from applications.extensions.init_tasks import tb_jyxt_land, tb_spt_land, tb_check_land, tb_jyxt_notice
from applications.models import AdminLog, JyxtLand
from applications.schemas import LogOutSchema
from applications.common.curd import model_to_dicts

bp = Blueprint('jyxt_info', __name__, url_prefix='/nx_jyxt')


# 日志管理
@bp.get('/')
@authorize("system:log:main")
def index():
    return render_template('system/admin_log/main.html')


# 登录日志
@bp.get('/loginLog')
@authorize("system:log:main")
def login_log():
    # orm查询
    # 使用分页获取data需要.items
    log = AdminLog.query.filter_by(url='/passport/login').order_by(desc(AdminLog.create_time)).layui_paginate()
    count = log.total
    return table_api(data=model_to_dicts(schema=LogOutSchema, data=log.items), count=count)


# 操作日志
@bp.get('/operateLog')
@authorize("system:log:main")
def operate_log():
    # orm查询
    # 使用分页获取data需要.items
    log = AdminLog.query.filter(
        AdminLog.url != '/passport/login').order_by(
        desc(AdminLog.create_time)).layui_paginate()
    count = log.total
    return table_api(data=model_to_dicts(schema=LogOutSchema, data=log.items), count=count)


@bp.route('/update_land_sfts/<ZYID>')
def update_land_sfts(ZYID):
    if not ZYID:
        return "请输入公告ID"
    land = JyxtLand.query.filter(JyxtLand.ZYID == ZYID).first()
    if not land:
        return "资源ID不存在"
    else:
        land.sfts = 1
        db.session.commit()
    return jsonify(land)


@bp.route('/check_land')
def check_land():
    tb_jyxt_land()  # 同步交易系统成交宗地信息
    tb_spt_land()  # 同步跟湖北省公共资源交易平台成交宗地尽心
    tb_check_land()  # 进行数据比对并发送邮件
    return '检测公共信息同步情况成功!'


@bp.route('/update_jyxt_land')  # 获取交易系统成交的宗地信息
def update_jyxt_land_info():
    tb_jyxt_land()
    return '更新交易系统成交公示信息成功!'


@bp.route('/update_jyxt_notice')
def query_jyxt_notice():  # 同步交易系统数据
    tb_jyxt_notice()
    return '交易系统公告信息同步成功!'
